import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from "vuex-persistedstate"

Vue.use(Vuex)

const store = new Vuex.Store({
	plugins: [
		persistedState({
			storage: {
				getItem: key => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: key => uni.removeStorageSync(key)
			}
		})
	],
	state: {
		cart: []
	},
	mutations: {
		PUSH_CART(state, payload) {
			let has = state.cart.find(item => item.id === payload.id)
			if (!has) {
				state.cart.push(payload)
			} else {
				state.cart.forEach(item => {
					if (item.id === payload.id) {
						item.number = payload.number
					}
				})
			}

			// 过滤0
			state.cart = state.cart.filter(item => item.number > 0)
		},
		CLEAN_CART(state) {
			state.cart = []
		}
	},
	getters: {
		parseNum(state) {
			return state.cart.reduce((initVal, current) => {
				return initVal + parseInt(current.number)
			}, 0)
		}
	}
})

export default store
